package member

import (
    "time"
	"dhfshop/models/member"
	"dhfshop/domain/member"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

type IntegralController struct {
	base.BaseController
}

// 冻结积分
func (this *IntegralController) FreezesIntegral() {
	v := struct {
		Value        int      `form:"value" valid:"Required"`
		Remark       string   `form:"remark"`
		RelateUserId int64    `form:"relate_user_id" valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//
	oldAccount, err := member.GetAccountById(int64(curUserId))
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	logId, err := memberlayer.FreezesIntegral(partnerId,curUserId,oldAccount,v.Value,"")
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		IntegralLogId int64  `json:"integral_log_id"`
	    Created   time.Time  `json:"created"`
	}{IntegralLogId: logId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
		
// 解冻积分
func (this *IntegralController) UnfreezesIntegral() {
	v := struct {
		Value        int      `form:"value" valid:"Required"`
		Remark       string   `form:"remark"`
		RelateUserId int64    `form:"relate_user_id" valid:"Required"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	//
	oldAccount, err := member.GetAccountById(int64(curUserId))
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	logId, err := memberlayer.UnfreezesIntegral(partnerId,curUserId,oldAccount,v.Value,"")
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		IntegralLogId int64  `json:"integral_log_id"`
	    Created   time.Time  `json:"created"`
	}{IntegralLogId: logId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 积分变动日志查询
func (this *IntegralController) IntegralLogList() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := member.GetAllIntegralLogs(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64                 `json:"total_count"`
		IntegralLogs []*member.IntegralLog `json:"integral_logs"`
	}{TotalCount: cnt, IntegralLogs: l}
	this.Data["json"] = r
	this.ServeJSON()
}

